import 'dart:async';

import 'package:audio_session/audio_session.dart';
import 'package:date_format/date_format.dart';
import 'package:flip_card/flip_card.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_dingding/core/widget/custom_app_bar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:just_audio/just_audio.dart';

import 'events.dart';

class THWorksetScreen extends StatelessWidget {
  const THWorksetScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: customAppbar(context: context, title: '考勤打卡'),
      // appBar: AppBar(
      //   title: Text(
      //     "",
      //     style: TextStyle(color: Colors.black),
      //   ),
      //   actions: [],
      // ),
      body: THWorksetBody(),
    );
  }
}

class THWorksetBody extends StatefulWidget {
  @override
  _THWorksetBodyState createState() => _THWorksetBodyState();
}

class _THWorksetBodyState extends State<THWorksetBody>
    with SingleTickerProviderStateMixin {
  GlobalKey<FlipCardState> _flipCardKey = GlobalKey<FlipCardState>();

  late AnimationController _animationController;

  bool _show = false;

  late Timer _timer;

  String _currentTime = formatDate(DateTime.now(), [HH, ':', nn, ':', ss]);

  String _downTime = formatDate(DateTime.now(), [HH, ':', nn, ':', ss]);

  late AudioPlayer _player;

  Color kTHPrimary = Color(0xFF005EFF);
  final Color kTHNormal = Color(0xFFF5F5F5);

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
        vsync: this, duration: Duration(milliseconds: 2000));

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _currentTime = formatDate(DateTime.now(), [HH, ':', nn, ':', ss]);
      });
    });

    _player = AudioPlayer();
    _player.playerStateStream.listen((state) {
      switch (state.processingState) {
        case ProcessingState.completed:
          _player.seek(Duration.zero, index: _player.effectiveIndices?.first);
          _player.stop();
          break;
        case ProcessingState.idle:
          break;
        case ProcessingState.loading:
          break;
        case ProcessingState.buffering:
          break;
        case ProcessingState.ready:
          break;
      }
    });
    _init();
  }

  _init() async {
    final session = await AudioSession.instance;
    await session.configure(AudioSessionConfiguration.music());
    try {
      // await _player.setAudioSource(_playlist);
      // var duration =
      await _player.setAsset('assets/sound/on_duty.mp3');
    } catch (e) {
      // catch load errors: 404, invalid url ...
      print("An error occured $e");
    }
  }

  @override
  void dispose() {
    if (null != _timer && _timer.isActive) {
      _timer.cancel();
    }

    if (null != _animationController) {
      _animationController.dispose();
    }

    if (null != _player) {
      _player.pause();
      _player.dispose();
    }

    super.dispose();
  }

  void _onClick() {
    setState(() {
      _show = true;
    });

    if (_player.playing) {
      return;
    }

    Future.delayed(Duration.zero, () {
      _animationController.repeat();

      Future.delayed(Duration(seconds: 3), () {
        setState(() {
          _downTime = formatDate(DateTime.now(), [HH, ':', nn, ':', ss]);
          _animationController.stop();
          _player.play();
          _flipCardKey.currentState?.toggleCard();
          _show = false;
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 20.w).copyWith(top: 20.h),
        child: Column(
          children: [_buildFlipCard()],
        ),
      ),
    );
  }

  _buildFlipCard() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Card(
          elevation: 0.0,
          child: Container(
            margin: EdgeInsets.symmetric(horizontal: 20.w),
            padding: EdgeInsets.symmetric(vertical: 20.w),
            child: Row(
              children: [
                Expanded(
                    flex: 4,
                    child: Container(
                      child: Row(
                        children: [
                          ClipOval(
                            child: Container(
                              width: 120.r,
                              height: 120.r,
                              alignment: Alignment.center,
                              color: kTHPrimary,
                              child: Text(
                                "江景",
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 32.sp,
                                ),
                              ),
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(left: 20.w),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  "江景",
                                  style: TextStyle(fontSize: 32.sp),
                                ),
                                Row(
                                  children: [
                                    Text("MOOSE"),
                                    Padding(
                                      padding: EdgeInsets.only(left: 10.w),
                                      child: Text(
                                        "(查看规则)",
                                        style: TextStyle(color: kTHPrimary),
                                      ),
                                    ),
                                  ],
                                )
                              ],
                            ),
                          )
                        ],
                      ),
                    )),
                Expanded(
                    flex: 1,
                    child: Container(
                      child: Text(
                        "申请",
                        style: TextStyle(fontSize: 32.sp),
                      ),
                    )),
              ],
            ),
          ),
        ),
        FlipCard(
            key: _flipCardKey,
            front: Card(
              elevation: 0.0,
              child: Column(
                children: [
                  Container(
                    margin: EdgeInsets.only(
                      top: 20.h,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Container(
                          width: 250.w,
                          padding: EdgeInsets.symmetric(
                              vertical: 10.h, horizontal: 10.w),
                          margin: EdgeInsets.only(left: 10.w),
                          decoration: BoxDecoration(
                              color: kTHNormal,
                              borderRadius:
                              BorderRadius.all(Radius.circular(10.w))),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                "上班08:30",
                                style: TextStyle(fontSize: 32.sp),
                              ),
                              Row(
                                children: [
                                  SvgPicture.asset(
                                    'assets/icons/icon_right.svg',
                                    width: 60.w,
                                    color: kTHPrimary,
                                  ),
                                  Text(
                                    "08:36已打卡",
                                    style: TextStyle(fontSize: 28.sp),
                                  )
                                ],
                              ),
                            ],
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: Container(
                            padding: EdgeInsets.symmetric(
                                vertical: 10.w, horizontal: 10.w),
                            margin:
                            EdgeInsets.only(left: 10.w, right: 10.w),
                            decoration: BoxDecoration(
                                color: kTHNormal,
                                borderRadius:
                                BorderRadius.all(Radius.circular(10.w))),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  "下班 18:30(弹性)",
                                  style: TextStyle(fontSize: 32.sp),
                                ),
                                Row(
                                  children: [
                                    SvgPicture.asset(
                                      'assets/icons/icon_right.svg',
                                      width: 60.w,
                                      color: kTHPrimary,
                                    ),
                                    Row(
                                      children: [
                                        Text(
                                          "08:36已打卡",
                                          style: TextStyle(fontSize: 28.sp),
                                        ),
                                        Text(
                                          "更新打卡",
                                          style: TextStyle(
                                              fontSize: 28.sp,
                                              color: kTHPrimary),
                                        ),
                                      ],
                                    )
                                  ],
                                ),
                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(top: 120.h),
                    child: Stack(
                      children: [
                        Center(
                          child: GestureDetector(
                            onTap: _onClick,
                            child: ClipOval(
                              child: Container(
                                width: 360.r,
                                height: 360.r,
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  color: kTHPrimary,
                                  gradient: LinearGradient(
                                      begin: Alignment.topCenter,
                                      end: Alignment.topCenter,
                                      colors: [
                                        kTHPrimary.withOpacity(0.8),
                                        kTHPrimary.withOpacity(1),
                                      ]),
                                ),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text(
                                      "上班打卡",
                                      style: TextStyle(
                                          color: Colors.white, fontSize: 38.sp),
                                    ),
                                    Text(_currentTime,
                                        style: TextStyle(
                                            color: Colors.white, fontSize: 38.sp)),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ),
                        Center(
                          child: _show
                              ? RotationTransition(
                            turns: _animationController,
                            child: ClipOval(
                              child: Container(
                                width: 360.r,
                                height: 360.r,
                                decoration: BoxDecoration(
                                  gradient: SweepGradient(colors: [
                                    Colors.white.withOpacity(0.4),
                                    Colors.white.withOpacity(0.6),
                                  ]),
                                ),
                              ),
                            ),
                          )
                              : Container(),
                        )
                      ],
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(
                      top: 40.h,
                      bottom: 40.h,
                    ),
                    child: Text("已进入考勤范围 MOOSE"),
                  ),
                ],
              ),
            ),
            back: Card(
              elevation: 0.0,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 20.w),
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              "下班打卡成功",
                              style: TextStyle(fontSize: 32.sp),
                            ),
                            Padding(
                              padding: EdgeInsets.all(10.w),
                              child: Text(
                                "打卡时间 $_downTime",
                                style: TextStyle(fontSize: 32.sp),
                              ),
                            ),
                            SizedBox(height: 10.h),
                            ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                  backgroundColor: kTHPrimary,
                                  shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(90)
                                  )
                              ),
                              onPressed: () {
                                Get.off(() => TableEventsExample());
                              },
                              child: Text('查看打卡记录')
                            )
                          ],
                        ),
                        GestureDetector(
                          child: Icon(Icons.close),
                          onTap: () {
                            // _flipCardKey.currentState?.toggleCard();
                          },
                        )
                      ],
                    )
                  ],
                ),
              ),
            )
        ),
      ],
    );
  }
}
